<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter(0)">
        总订单({{ orderTotal.orderTotal }})
      </el-button>
      <el-button v-waves value="1" class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter(1)">
        运输中({{ orderTotal.shippingOrder }})
      </el-button>
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter(2)">
        已完成({{ orderTotal.doneOrder }})
      </el-button>
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter(-1)">
        取消数({{ orderTotal.cancleTotal }})
      </el-button>
    </div>
    <div class="filter-container" style="padding: 16px 0;">
      <!-- <el-input v-model="listQuery.driverName" placeholder="司机" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.ownerName" placeholder="货主" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="handleFilter" /> -->

      <el-input v-model="search.orderNo" placeholder="订单编号" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="searchList" />
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>-->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        发布订单
      </el-button>
      <!--<el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :row-class-name="tableRowClassName"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="订单编号" prop="id" align="center" width="118">
        <template slot-scope="{row}">
          <span>{{ row.orderNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货主名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ownerName }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="货主手机" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="司机名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.driverName }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="司机手机" align="center">
        <template slot-scope="{row}">
          <span>{{ row.driverPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="始发地" align="center">
        <template slot-scope="{row}">
          <span>{{ row.from.city }}</span>
        </template>
      </el-table-column>
      <el-table-column label="目的地" align="center">
        <template slot-scope="{row}">
          <span>{{ row.to.city }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="预计到货时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.arrivalTime.start | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.state | orderState(row.state) }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Imp" width="80px">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" width="200px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <!-- <el-button v-if="row.status!='draft'" size="mini" @click="getDetail(row.id)">
            详情
          </el-button> -->
          <div v-if="row.type==1">
            <div v-if="row.state==0">
              <el-button type="primary" size="mini" @click="openDetail(row.id,'update')">
                编辑
              </el-button>
              <el-button v-if="row.state==0" size="mini" type="danger" @click="close(row.id,0)">
                关闭
              </el-button>
            </div>
            <div v-else>
              <el-button size="mini" @click="openDetail(row.id,'detail')">
                查看详情
              </el-button>
              <el-button v-if="row.state==-6" size="mini" type="success" @click="close(row.id,1)">
                开启
              </el-button>
              <el-button v-if="row.state==1" size="mini" type="warning" @click="operation(row.id,2)">
                申请取消订单
              </el-button>
              <el-button v-if="row.state==-4" size="mini" type="success" @click="operation(row.id,0)">
                同意
              </el-button>
              <el-button v-if="row.state==-4" size="mini" type="danger" @click="operation(row.id,3)">
                拒绝
              </el-button>
              <el-button v-if="row.state==5" size="mini" type="success" @click="operation(row.id,1)">
                确认收货
              </el-button>
            </div>
          </div>
          <div v-else>
            <el-button size="mini" @click="openDetail(row.id,'detail')">
              查看详情
            </el-button>
          </div>
          <!-- <el-button size="mini" type="danger" @click="handleModifyStatus(row,'deleted')"> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="right" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="订单预计装货时间" prop="shipmentTime">
          <el-date-picker
            v-model="temp.shipmentTime.start"
            :readonly="dialogStatus=='detail'"
            :picker-options="pickerOptions0"
            placeholder="选择日期"
            type="datetime"
            value-format="timestamp"
            format="yyyy-MM-dd HH 时"
          />
          <!-- <el-time-select
            v-model="shipmentTime.time"
            align="center"
            :picker-options="{
              start: '00:00',
              step: '01:00',
              end: '24:00'
            }"
            placeholder="选择时间"
            @change="changeTime"
          /> -->
          <!-- <el-date-picker v-model="temp.shipmentTime.start" type="datetime" placeholder="Please pick a date" /> -->
        </el-form-item>
        <!-- <el-form-item label="订单接单最晚时间" prop="timestamp">
          <el-date-picker v-model="temp.shipmentTime.end" type="datetime" placeholder="Please pick a date" />
        </el-form-item> -->
        <el-form-item label="订单预计送达时间" prop="arrivalTime">

          <el-date-picker
            v-model="temp.arrivalTime.start"
            :readonly="dialogStatus=='detail'"
            :picker-options="pickerOptions0"
            placeholder="选择日期"
            type="datetime"
            value-format="timestamp"
            format="yyyy-MM-dd HH 时"
          />
          <!-- <el-date-picker v-model="temp.arrivalTime.start" type="datetime" placeholder="Please pick a date" /> -->
        </el-form-item>
        <!-- <el-form-item label="订单预计送达最晚时间" prop="timestamp">
          <el-date-picker v-model="temp.arrivalTime.end" type="datetime" placeholder="Please pick a date" />
        </el-form-item> -->

        <el-form-item label="货物名称" prop="freightName">
          <el-input v-model="temp.freightName" placeholder="请输入货物名称" :readonly="dialogStatus=='detail'" />
        </el-form-item>
        <el-form-item label="货物最小重量" prop="freightWeight.min">
          <div v-if="dialogStatus!='detail'">
            <el-input-number v-model="temp.freightWeight.min" :min="0" label="描述文字" :readonly="dialogStatus=='detail'" @change="handleChange" />吨
          </div>
          <div v-else-if="dialogStatus=='detail'" style="display: flex;">
            <el-input v-model="temp.freightWeight.min" placeholder="货物最小重量" :readonly="dialogStatus=='detail'" />吨
          </div>
        </el-form-item>
        <el-form-item label="货物最大重量" prop="freightWeight.max">
          <div v-if="dialogStatus!='detail'">
            <el-input-number v-model="temp.freightWeight.max" :min="0" label="描述文字" :readonly="dialogStatus=='detail'" @change="handleChange" />吨
          </div>
          <div v-else-if="dialogStatus=='detail'" style="display: flex;">
            <el-input v-model="temp.freightWeight.max" placeholder="货物最大重量" :readonly="dialogStatus=='detail'" />吨
          </div>
        </el-form-item>

        <el-form-item label="货物最小体积" prop="freightBulk.min">
          <div v-if="dialogStatus!='detail'">
            <el-input-number v-model="temp.freightBulk.min" :min="0" label="描述文字" :readonly="dialogStatus=='detail'" @change="handleChange" />方
          </div>
          <div v-else-if="dialogStatus=='detail'" style="display: flex;">
            <el-input v-model="temp.freightBulk.min" placeholder="货物最小体积" :readonly="dialogStatus=='detail'" />方
          </div>
        </el-form-item>
        <el-form-item label="货物最大体积" prop="freightBulk.max">
          <div v-if="dialogStatus!='detail'">
            <el-input-number v-model="temp.freightBulk.max" :min="0" label="描述文字" @change="handleChange" />方
          </div>
          <div v-else-if="dialogStatus=='detail'" style="display: flex;">
            <el-input v-model="temp.freightBulk.max" placeholder="货物最大体积" :readonly="dialogStatus=='detail'" />方
          </div>
        </el-form-item>
        <el-form-item label="出发地地址" prop="from.city">
          <el-cascader
            v-if="dialogStatus!='detail'"
            v-model="fromShowcity"
            size="large"
            :options="sendaddresss"
            style="width:217px;"
            :readonly="dialogStatus=='detail'"
            clearable
            @change="handleChanges"
          />
          <el-input v-else-if="dialogStatus=='detail'" v-model="temp.from.city" placeholder="详细地址" :readonly="dialogStatus=='detail'" />
          <el-input v-model="temp.from.address" placeholder="详细地址" :readonly="dialogStatus=='detail'" />
        </el-form-item>
        <el-form-item label="收货地地址" prop="to.city">
          <el-cascader
            v-if="dialogStatus!='detail'"
            v-model="toShowcity"
            :readonly="dialogStatus=='detail'"
            size="large"
            :options="sendaddresss"
            style="width:217px;"
            clearable
            @change="handleChanges"
          />
          <el-input v-else-if="dialogStatus=='detail'" v-model="temp.to.city" placeholder="详细地址" :readonly="dialogStatus=='detail'" />
          <el-input v-model="temp.to.address" placeholder="详细地址" :readonly="dialogStatus=='detail'" />
        </el-form-item>

        <el-form-item label="用车类型" prop="useVehicleType">
          <el-input v-if="dialogStatus=='detail'" v-model="temp.useVehicleType" placeholder="请输入用车类型" :readonly="dialogStatus=='detail'" />
          <el-select v-else v-model="temp.useVehicleType" class="filter-item" placeholder="请选择">
            <el-option v-for="item in level7" :key="item.key" :label="item.content" :value="item.content" />
          </el-select>
        </el-form-item>
        <el-form-item label="车长" prop="vehicleLen">
          <el-input v-model="temp.vehicleLen" placeholder="请输入车长" :readonly="dialogStatus=='detail'" />
        </el-form-item>
        <el-form-item label="车型" prop="vehicleModel">
          <el-input v-model="temp.vehicleModel" placeholder="请输入车型" :readonly="dialogStatus=='detail'" />
        </el-form-item>
        <el-form-item label="几装几卸" prop="hand">
          <el-input v-if="dialogStatus=='detail'" v-model="temp.hand" placeholder="" :readonly="dialogStatus=='detail'" />
          <el-select v-else v-model="temp.hand" class="filter-item" placeholder="请选择">
            <el-option v-for="item in level2" :key="item.key" :label="item.content" :value="item.content" />
          </el-select>
        </el-form-item>

        <el-form-item label="特殊要求" prop="specialAsk">
          <el-input v-model="temp.specialAsk" placeholder="请输入特殊要求" :readonly="dialogStatus=='detail'" />
          <!-- <el-input v-model="temp.specialAsk" placeholder="请输入特殊要求" :readonly="dialogStatus=='detail'" /> -->
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="temp.remarks" placeholder="请输入备注" :readonly="dialogStatus=='detail'" />
        </el-form-item>
        <el-form-item label="运费" prop="freight">
          <el-input v-model="temp.freight" placeholder="Please input" :readonly="dialogStatus=='detail'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button v-if="dialogStatus!='detail'" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="详情">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="表头" />
        <el-table-column prop="value" label="值" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle, getTotal, getDetail, searchList, close, operation, getSetting } from '@/api/order'
// import { fetchList, fetchPv, updateArticle, getTotal, getDetail, searchList, close, operation, getSetting } from '@/api/order'

import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

// const orderStateDate = []
// orderStateDate[-6] = '关闭订单'
// orderStateDate[-1] = '货主取消订单'
// orderStateDate[-2] = '货主申请取消订单'
// orderStateDate[-4] = '司机取消订单'
// orderStateDate[0] = '待接货'
// orderStateDate[1] = '已接单'
// orderStateDate[2] = '已装货'
// orderStateDate[3] = '待发货'
// orderStateDate[4] = '待收货'
// orderStateDate[5] = '已达到'
// orderStateDate[6] = '已完成'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    parseTime: parseTime,
    orderState(type) {
      const orderStateDate = {
        '-6': '关闭订单',
        '-1': '货主取消订单',
        '-2': '货主申请取消订单',
        '-4': '司机取消订单',
        '0': '待接单',
        '1': '待接货',
        '2': '已装货',
        '3': '待发货',
        '4': '待收货',
        '5': '已到达',
        '6': '已完成'
      }
      return orderStateDate[type]
    }
  },
  data() {
    return {
      //        禁止选择当前日期之前的日期

      pickerOptions0: {
        disabledDate: (time) => {
          return time.getTime() <= Date.now() - 8.64e7
        }
      },
      pickerOptions1: {
        disabledDate: (time) => {
          if (this.arrivalTime !== '') {
            const currentTime = this.shipmentTime
            return time.getTime() > currentTime
          } else {
            return time.getTime() > Date.now()
          }
        }
      },

      level1: [],
      level2: [],
      level3: [],
      level7: [],
      CodeToText,
      TextToCode,
      sendaddresss: provinceAndCityData,
      selectedOptions: [],
      sendOptions: [],
      sendreturnprovince: '',
      sendreturncity: '',
      sendreturnregion: '',
      tableKey: 0,
      list: null,
      orderTotal: {
        orderTotal: 0,
        shippingOrder: 0,
        doneOrder: 0,
        cancleTotal: 0
      },
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        importance: undefined,
        title: undefined,
        type: 0,
        orderId: undefined,
        driverName: undefined

        // sort: '+id'
      },
      search: {
        orderNo: '',
        pageNum: 1,
        pageSize: 20
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      shipmentTime: {
        date: new Date(),
        time: 0
      },
      arrivalTime: {
        date: new Date(),
        time: 0
      },

      toShowcity: [],
      fromShowcity: [],
      temp: {
        arrivalTime: {
          end: new Date(),
          start: new Date()
        },
        freight: 0,
        freightBulk: {
          max: 1,
          min: 1
        },
        freightName: '',
        freightWeight: {
          max: 1,
          min: 1
        },
        from: {
          address: '',
          city: null,
          province: ''
        },
        hand: '',
        remarks: '',
        shipmentTime: {
          end: new Date(),
          start: new Date()
        },
        specialAsk: '',
        to: {
          address: '',
          city: null,
          province: ''
        },
        useVehicleType: '',
        vehicleLen: '',
        vehicleModel: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getTotal()
    this.getList()
    this.getOption()
  },
  // mounted() {
  //   // 通过this.datas获取地址赋值到页面
  //   this.sendOptions[0] = (this.TextToCode[this.datas.AddresserProvince].code)
  //   if (this.datas.AddresserProvince !== this.datas.AddresserCity) {
  //     this.datas.AddresserCity = this.datas.AddresserCity
  //   } else {
  //     this.datas.AddresserCity = '市辖区'
  //   }
  //   this.sendOptions[1] = (this.TextToCode[this.datas.AddresserProvince][this.datas.AddresserCity].code)

  //   this.sendOptions[2] = (this.TextToCode[this.datas.AddresserProvince][this.datas.AddresserCity][this.datas.AddresserRegion].code)

  //   this.sendOptions = [this.ruleForm.sendOptions[0], this.ruleForm.sendOptions[1], this.ruleForm.sendOptions[2]]

  //   // this.sendOptions2[0] = (this.TextToCode[this.datas.AddresserProvince].code)
  //   // if (this.datas.AddresserProvince !== this.datas.AddresserCity) {
  //   //   this.datas.AddresserCity = this.datas.AddresserCity
  //   // } else {
  //   //   this.datas.AddresserCity = '市辖区'
  //   // }
  //   // this.sendOptions[1] = (this.TextToCode[this.datas.AddresserProvince][this.datas.AddresserCity].code)

  //   // this.sendOptions[2] = (this.TextToCode[this.datas.AddresserProvince][this.datas.AddresserCity][this.datas.AddresserRegion].code)

  //   // this.sendOptions = [this.ruleForm.sendOptions[0], this.ruleForm.sendOptions[1], this.ruleForm.sendOptions[2]]
  // },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (row.type === 1) {
        return 'warning-row'
      }
      return ''
    },
    getList() {
      console.log(this.listQuery, '123456', this.listQuery.type)
      this.listLoading = true
      console.log(this.listQuery.pageNum)
      fetchList(this.listQuery, this.listQuery.type).then(response => {
        console.log(response.result)
        this.list = response.result
        this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getTotal() {
      this.listLoading = true
      getTotal().then(response => {
        this.orderTotal = response.result
        this.total=response.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter(typeDate) {
      if (!isNaN(typeDate)) {
        console.log('sss' + typeDate)
        this.listQuery.type = typeDate
      } else {
        console.log(typeDate)
        this.listQuery.type = ''
      }
      const arr = this.listQuery
      for (const key in arr) {
        // 去除对象内多余的空值key
        if (arr[key] === '') {
          delete arr[key]
        }
      }
      this.listQuery = arr
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.shipmentTime = {
        date: new Date(),
        time: 0
      }
      this.arrivalTime = {
        date: new Date(),
        time: 0
      }
      this.sendreturnprovince = ''
      this.sendreturncity = ''
      this.sendreturnregion = ''
      this.toShowcity = []
      this.fromShowcity = []
      this.temp = {
        arrivalTime: {
          end: '',
          start: ''
        },
        freight: 0,
        freightBulk: {
          max: 1,
          min: 1
        },
        freightName: '',
        freightWeight: {
          max: 1,
          min: 1
        },
        from: {
          address: '',
          city: '',
          province: ''
        },
        hand: '',
        remarks: '',
        shipmentTime: {
          end: '',
          start: ''
        },
        specialAsk: '',
        to: {
          address: '',
          city: '',
          province: ''
        },
        useVehicleType: '',
        vehicleLen: '',
        vehicleModel: ''
      }
    },
    handleCreate() {
      this.listLoading = true
      this.$nextTick(() => {
        this.temp.from.city = ''
        this.temp.to.city = ''
        this.resetTemp()
        // this.temp.from.city = []
        // this.temp.to.city = []
        console.log(this.temp)
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.listLoading = false
        if (this.$refs['dataForm'] !== undefined) {
          this.$refs['dataForm'].resetFields()
        }
        this.$refs['dataForm'].clearValidate()
      })
    },
    getOption() {
      getSetting().then(response => {
        this.level1 = response.result[0].infos
        this.level2 = response.result[1].infos
        this.level3 = response.result[2].infos
        this.level7 = response.result[6].infos
        this.$forceUpdate()
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 1.5 * 1000)
      })
    },
    createData() {
      // this.$refs['dataForm'].validate((valid) => {
      // if (valid) {
      // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
      // this.temp.author = 'vue-element-admin'
      var comfirmData = this.temp
      console.log(this.arrivalTime)
      console.log(this.shipmentTime)
      if (comfirmData.shipmentTime.start !== 0) {
        console.log(this.temp)
        comfirmData.shipmentTime.start = this.temp.shipmentTime.start / 1000
        comfirmData.shipmentTime.end = this.temp.shipmentTime.start
      }
      if (comfirmData.arrivalTime.start !== 0) {
        comfirmData.arrivalTime.start = this.temp.arrivalTime.start / 1000
        comfirmData.arrivalTime.end = this.temp.arrivalTime.start
      }
      if (this.fromShowcity[0]) {
        comfirmData.from.province = CodeToText[this.fromShowcity[0]]
        if (CodeToText[this.fromShowcity[1]] === '市辖区') {
          comfirmData.from.city = this.temp.from.province + '|' + this.temp.from.province
        } else {
          comfirmData.from.city = this.temp.from.province + '|' + CodeToText[this.fromShowcity[1]]
        }
      }
      if (comfirmData.specialAsk) {
        comfirmData.specialAsk = this.temp.specialAsk.split(',')
      } else {
        comfirmData.specialAsk = []
      }
      if (this.toShowcity[0]) {
        comfirmData.to.province = CodeToText[this.toShowcity[0]]
        if (CodeToText[this.toShowcity[1]] === '市辖区') {
          comfirmData.to.city = this.temp.to.province + '|' + this.temp.to.province
        } else {
          comfirmData.to.city = this.temp.to.province + '|' + CodeToText[this.toShowcity[1]]
        }
      } else {
        console.log(this.temp)
        if (this.temp.shipmentTime.start !== 0) {
          this.temp.shipmentTime.start = this.temp.shipmentTime.start * 1000
        }
        if (this.temp.arrivalTime.start !== 0) {
          this.temp.arrivalTime.start = this.temp.arrivalTime.start * 1000
        }
        this.$message.error('请填写完整信息')
        return false
      }

      createArticle(comfirmData).then(response => {
        console.log(response)

        if (response.code === 200) {
          // this.list.unshift(this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            duration: 2000
          })

          this.$nextTick(() => {
            this.resetTemp()
            this.getList()
            this.getTotal()
            this.$refs['dataForm'].resetFields()
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          console.log(this.temp)
          this.$message.error(response.message)
        }
      })
    },
    handleUpdate(row) {
      console.log(row)
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      // this.dialogPvVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    openDetail(id, type) {
      this.listLoading = true

      this.dialogStatus = type

      getDetail(id).then(response => {
        this.temp = response.result
        this.temp.specialAsk = this.temp.specialAsk.toString()
        if (type === 'update') {
          this.fromShowcity = this.temp.from.city.split('|')
          console.log(this.fromShowcity)
          if (this.fromShowcity[1] === this.fromShowcity[0]) {
            this.fromShowcity[1] = '市辖区'
          }

          console.log(this.temp)

          this.fromShowcity[1] = (TextToCode[this.fromShowcity[0]][this.fromShowcity[1]].code)
          this.fromShowcity[0] = (TextToCode[this.fromShowcity[0]].code)
          this.toShowcity = this.temp.to.city.split('|')
          if (this.toShowcity[1] === this.toShowcity[0]) {
            this.toShowcity[1] = '市辖区'
          }
          console.log(this.temp.to.city)
          this.toShowcity[1] = (TextToCode[this.toShowcity[0]][this.toShowcity[1]].code)
          this.toShowcity[0] = (TextToCode[this.toShowcity[0]].code)
        }

        this.temp.shipmentTime.start = this.temp.shipmentTime.start * 1000
        this.temp.arrivalTime.start = this.temp.arrivalTime.start * 1000

        setTimeout(() => {
          this.listLoading = false
          this.dialogFormVisible = true
          this.$nextTick(() => {
          })
        }, 1.5 * 1000)
      })
    },
    getDetail(pv) {
      // getDetail(pv).then(response => {
      //   var arr = response.result
      //   console.log(arr)
      //   const showDetail = []
      //   for (const key in arr) {
      //     showDetail.push({ 'key': key, 'value': arr[key] })
      //     console.log(key + '---' + arr[key])
      //   }
      //   this.pvData = showDetail
      //   this.dialogPvVisible = true
      // })
    },
    updateData() {
      this.temp.shipmentTime.start = this.temp.shipmentTime.start / 1000
      this.temp.shipmentTime.end = this.temp.shipmentTime.start
      this.temp.arrivalTime.start = this.temp.arrivalTime.start / 1000
      this.temp.arrivalTime.end = this.temp.arrivalTime.start
      this.temp.from.province = CodeToText[this.fromShowcity[0]]
      this.temp.specialAsk = this.temp.specialAsk.split(',')

      if (CodeToText[this.fromShowcity[1]] === '市辖区') {
        this.temp.from.city = this.temp.from.province + '|' + this.temp.from.province
      } else {
        this.temp.from.city = this.temp.from.province + '|' + CodeToText[this.fromShowcity[1]]
      }

      this.temp.to.province = CodeToText[this.toShowcity[0]]
      if (CodeToText[this.toShowcity[1]] === '市辖区') {
        this.temp.to.city = this.temp.to.province + '|' + this.temp.to.province
      } else {
        this.temp.to.city = this.temp.to.province + '|' + CodeToText[this.toShowcity[1]]
      }
      updateArticle(this.temp, this.temp.id).then(() => {
        // this.list.unshift(this.temp)
        this.dialogFormVisible = false

        this.getList()
        this.getTotal()
        this.$notify({
          title: 'Success',
          message: 'Created Successfully',
          type: 'success',
          duration: 2000
        })
      })

      this.$nextTick(() => {
        this.resetTemp()
        this.$refs['dataForm'].clearValidate()
      })
      // this.$refs['dataForm'].validate((valid) => {
      //   if (valid) {
      //     const tempData = Object.assign({}, this.temp)
      //     tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
      //     updateArticle(tempData).then(() => {
      //       for (const v of this.list) {
      //         if (v.id === this.temp.id) {
      //           const index = this.list.indexOf(v)
      //           this.list.splice(index, 1, this.temp)
      //           break
      //         }
      //       }
      //       this.dialogFormVisible = false
      //       this.$notify({
      //         title: 'Success',
      //         message: 'Update Successfully',
      //         type: 'success',
      //         duration: 2000
      //       })
      //     })
      //   }
      // })
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'orderNo', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'orderNo', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    },
    handleChange(value) {

    },
    handleChanges(value) {
      console.log(value[0])
      console.log(value[1])
      this.sendreturnprovince = CodeToText[this.sendOptions[0]]
      if (CodeToText[this.sendOptions[1]] === '市辖区') {
        this.sendreturncity = this.sendreturnprovince
      } else {
        this.sendreturncity = CodeToText[this.sendOptions[1]]
      }
    },
    changeTime(value) {
      console.log(value)
    },

    // 搜索更新列表
    searchList() {
      this.listLoading = true
      searchList(this.search).then(response => {
        console.log(response.result)
        this.list = response.result
        // this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    close(val, type) {
      this.listLoading = true
      close(val, type).then(response => {
        this.getList()
        this.getTotal()
        console.log(response.result)
        // this.list = response.result
        // this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleSizeChange(val) {
      this.$emit('pagination', { page: this.currentPage, limit: val })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
    },
    handleCurrentChange(val) {
      this.$emit('pagination', { page: val, limit: this.pageSize })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
    },
    operation(id, type) {
      operation(id, type).then(response => {
        if (response.code === 200) {
          this.$message({
            message: '操作Success',
            type: 'success'
          })
          this.getList()
          this.getTotal()
        } else {
          this.$message.error(response.message)
          this.getList()
          this.getTotal()
        }
      })
    }
  }
}
</script>
<style scoped>
.tdContent{
  border: 1px solid #EBEEF5;
  width: 170px;
  height: 40px;
}
.tableTitle{
  display: inline-block;
  text-align: center;
}

</style>
<style>
.el-table .warning-row {
    background: oldlace;
  }

</style>
